
$(function() {
	var parameter = Base64.decode(UrlParm.parm("parameter"));
	var url = UrlParmValue(parameter).parm("url");
	var service_id = UrlParmValue(parameter).parm("service_id")
	//var service_url_id = UrlParmValue(parameter).parm("service_url_id")
	var service_name = UrlParmValue(parameter).parm("service_name");

	// 接口名称
	$("#id_api_name").val(service_name+"查询  ");
	// 接口地址
	$("#apiurl").val(url);

	$("#boxBtn").click(function() {
		requestClick();
	});
	
	//请求参数列表
	getApiRequestParametersInfo(service_id);
	
});  

function requestClick(){
	
	var parameter = Base64.decode(UrlParm.parm("parameter"));
	var url = UrlParmValue(parameter).parm("url");
	//var service_url_id = UrlParmValue(parameter).parm("service_url_id")
	var service_id = UrlParmValue(parameter).parm("service_id");
	var service_name = UrlParmValue(parameter).parm("service_name");
	
	$("#boxBtn").html('请求中...').attr('disabled','disabled');

	$("#feedback").html("").css({
		display : "none"
	});

	$("#response,#requestinfo").html('');

	var requesttypesel = $("#requesttypesel").val();
	var inputs = $("input[name=input-param]");
	var apiid = $("#apinamesel").val();

	var paraObj = {
		requesttypesel : requesttypesel,
		apiid : apiid
	};
	var params = {};
	
	var requestParam = "";//请求参数
	
	$.each(inputs, function() {
		var paraNameValue = $(this).val();
		var paraName = $(this).attr("data");
		if(paraName != 'id'){//特殊处理，id不需要传入后台查询,是拼接在url上面
			if(!trim(paraNameValue) == ''){
				params[paraName] = paraNameValue;
				requestParam += paraName+"="+paraNameValue+"&"
			}
		}
	});
	if(requestParam != ""){
		requestParam = requestParam.substring(0,requestParam.length-1);
	}
	
	var requestinfo = '';
	requestinfo = "请求地址：" + url + "/" + service_id+"<br/>";
	requestinfo += "请求参数："+requestParam+"<br/>";
	requestinfo += "请求方式：POST<br/>";

	$("#requestinfo").html(requestinfo);

	$.ajax({
		type : "get",
		url : "interface/interfaceTest",
		data : {
			"url" : url + "/" + service_id,
			"paraObj" : JSON.stringify(params)
		},
		dataType : "json",
		success : function(data) {
			$("#response").removeClass("xml").addClass("json");
			// var str = JSON.stringify(data,null, "\t");
			var str = JSON.stringify(data, null, 4);
			$("#response").html(str);
			hljs.highlightBlock($("#returnarea pre code").get(0));
		}
	});
	
	$("#boxBtn").html('发送请求').removeAttr('disabled');
}

function getApiRequestParametersInfo(service_id){
	$.ajax({
		type : "post",
		url :  "api/getApiRequestParametersInfo",
		data : {
			"service_id" : service_id
		},
		dataType : "json",
		success : function(data) {
			if (data.flag) {
				var datas = data.datas;
				$("#id_request_params").empty();
				var str = '<label for="params">请求参数：</label>'+
				          '<table class="table table-bordered table-striped table-condensed" id="params" style="font-size: 12px;">'+
				          	  '<tr><td>参数名</td><td>类型</td><td>是否必填</td><td>说明</td><td>值</td></tr>'+
				          	  '<tr><td>id</td><td>int</td><td>是</td><td>接口查询id</td><td><input name="input-param" class="form-control input-sm" type="text" readonly="readonly" data="id" value='+service_id+'></td></tr>';
				for(var i = 0 ; i < datas.length; i++){
					var data = datas[i];
					str += '<tr><td>'+data['columns']+'</td><td>'+data['type']+'</td><td>'+data['isRequired']+'</td><td>'+data['describes']+'</td><td><input name="input-param" class="form-control input-sm" data="'+data['columns']+'" type="text"></td></tr>';
				}
				str += '</table>';
				$("#id_request_params").append(str);
			}
		}
	});
}

function getPrefix(prefixIndex){
    var span = '    ';
    var output = [];
    for(var i = 0 ; i < prefixIndex; ++i){
        output.push(span);
    }
    return output.join('');
}

function html_encode(str) {
	var s = "";
	if (str.length == 0) return "";
	s = str.replace(/&/g, "&gt;");
	s = s.replace(/</g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	s = s.replace(/ /g, "&nbsp;");
	s = s.replace(/\'/g, "&#39;");
	s = s.replace(/\"/g, "&quot;");
	s = s.replace(/\n/g, "<br>");
	return s;
}

function formatXml(text){
    // 去掉多余的空格
    text = '\n' + text.replace(/(<\w+)(\s.*?>)/g,function($0, name, props)
    {
        return name + ' ' + props.replace(/\s+(\w+=)/g," $1");
    }).replace(/>\s*?</g,">\n<");

    // 把注释编码
    text = text.replace(/\n/g,'\r').replace(/<!--(.+?)-->/g,function($0, text)
    {
        var ret = '<!--' + escape(text) + '-->';
        // alert(ret);
        return ret;
    }).replace(/\r/g,'\n');

    // 调整格式
    var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
    var nodeStack = [];
    var output = text.replace(rgx,function($0,all,name,isBegin,isCloseFull1,isCloseFull2 ,isFull1,isFull2){
        var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/');
        // alert([all,isClosed].join('='));
        var prefix = '';
        if(isBegin == '!')
        {
            prefix = getPrefix(nodeStack.length);
        }
        else
        {
            if(isBegin != '/')
            {
                prefix = getPrefix(nodeStack.length);
                if(!isClosed)
                {
                    nodeStack.push(name);
                }
            }
            else
            {
                nodeStack.pop();
                prefix = getPrefix(nodeStack.length);
            }

        }
            var ret =  '\n' + prefix + all;
            return ret;
    });

    var prefixSpace = -1;
    var outputText = output.substring(1);
    // alert(outputText);

    // 把注释还原并解码，调格式
    outputText = outputText.replace(/\n/g,'\r').replace(/(\s*)<!--(.+?)-->/g,function($0, prefix,  text)
    {
        // alert(['[',prefix,']=',prefix.length].join(''));
        if(prefix.charAt(0) == '\r')
            prefix = prefix.substring(1);
        text = unescape(text).replace(/\r/g,'\n');
        var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix ) + '-->';
        // alert(ret);
        return ret;
    });

    return outputText.replace(/\s+$/g,'').replace(/\r/g,'\n');
}

function trim(str){ 
    return str.replace(/(^\s*)|(\s*$)/g, ""); 
}